<script lang="ts" name="Coc" setup>
import MenuBar from '@/views/components/menuBar/index.vue'
import AddTime from './components/addTime/index.vue'
import { openChildWindow } from '@/utils/windowTool'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

/*========================================>( 模型属性 )<========================================*/
//标题栏菜单
const menuBarMenus = ref<Array<any>>([
    {
        name: '设置',
        icon: 'setting',
        childrens: [
            { name: '管理标签', mark: 'labels', icon: 'tag' },
            { name: '全部清空', mark: 'clear', icon: 'clear' },
        ]
    },
    {
        name: '添加',
        icon: 'add',
        mark: 'add'
    }
])
//是否显示添加任务窗口
const showAddTime = ref<boolean>(false)
//任务列表
const tasks = ref<any>()
//活跃下标
const activeIndex = ref<number>()
//现在的mils
const nowMils = ref<number>(0)

/*========================================>( 作用域值 )<========================================*/
const _ipcs = {
    getData() {
        const { module, value } = window.ipcRenderer.sendSync('STORAGE-GET', { module: 'coc' })
        console.log('main', module, value)
        //如果所属本模块，更新模块设置数据 
        if (module == 'coc') {
            const storageTasks = value.tasks
            const res = []
            for (const group of storageTasks) {
                group.list = sortByTime(group.list)
                res.push(group)
            }
            tasks.value = res
            console.log('tasks.value', tasks.value)
        }
    },
    rmItem(id: string) {
        const { module, value } = window.ipcRenderer.sendSync('STORAGE-GET', { module: 'coc' })
        if (module == 'coc') {
            const storageTasks = value.tasks
            const afterTasks = []
            for (const group of storageTasks) {
                const item = group.list.find((e: any) => e.id === id)
                if (!item) {
                    afterTasks.push(group)
                    continue
                } else {
                    group.list = group.list.filter((e: any) => e.id !== id)
                    if (group.list.length) {
                        afterTasks.push(group)
                    } else {
                        //TODO 提示组自动删除
                    }
                }
            }
            window.ipcRenderer.sendSync('STORAGE-SAVE', {
                module: 'coc',
                data: { tasks: afterTasks }
            })
            _ipcs.getData()
        }
    },
    rmAll() {
        window.ipcRenderer.sendSync('STORAGE-SAVE', {
            module: 'coc',
            data: { tasks: [] }
        })
        _ipcs.getData()
    }
}
/*========================================>( 计算属性 )<========================================*/
//计算渲染数据
const taskInfo = computed(() => {
    //根据task，生成对应的剩余时间、百分比
    if (!nowMils.value) {
        return {}
    }
    const res: any = {}
    for (const group of tasks.value) {
        for (const item of group.list) {
            const { id, waitMils, createdMils } = item
            const space = createdMils + waitMils - nowMils.value
            if (space <= 0) {
                res[id] = { status: 0, rate: 100, remainStr: '已完成', remain: 0 }
            } else {
                // 计算各个时间单位
                let seconds = Math.floor(space / 1000);
                let minutes = Math.floor(seconds / 60);
                let hours = Math.floor(minutes / 60);
                let days = Math.floor(hours / 24);
                // 计算剩余的时间
                seconds = seconds % 60;
                minutes = minutes % 60;
                hours = hours % 24;

                const daystr = `${days}天`
                const hourstr = `${hours}小时`
                const minutestr = `${minutes}分钟`
                const secondstr = `${seconds}秒`

                const remainStr = `${days ? daystr : ''} ${hours ? hourstr : ''} ${(days && hours) || !minutes ? '' : minutestr} ${(days && hours) || (hours && minutes) ? '' : secondstr}`

                //计算比例，比例小于5默认5
                const rate = Math.floor((nowMils.value - createdMils) / waitMils * 100)
                res[id] = { status: 1, remain: space, remainStr, rate: rate < 5 ? 5 : rate }
            }
        }
    }
    return res
})
/*========================================>( 普通函数 )<========================================*/

const sortByTime = (arr: Array<any>) => {
    return [...arr].sort((a, b) => (a.createdMils + a.waitMils) - (b.createdMils + b.waitMils));
}

/*========================================>( 监听函数 )<========================================*/
//监听菜单
const handelBarMenusSelected = (mark: string) => {
    switch (mark) {
        case 'labels':
            openChildWindow({ hash: 'coc/labels', width: 500, height: 400 })
            break
        case 'add':
            showAddTime.value = true
            break
        case 'clear':
            proxy?.$modal.confirm(`您确认要清空所有任务吗？`).then(() => {
                _ipcs.rmAll()
                proxy?.$modal.msgSuccess('清除成功', 80)
            })
            break
        default:
            break
    }
}

//监听新任务窗口关闭
const handleAddTimeClose = () => {
    showAddTime.value = false
    _ipcs.getData()
}

//监听删除项目
const handleItemDelete = (id: string, status: boolean) => {
    if (status) {
        proxy?.$modal.confirm(`此任务尚未执行完成。您确定要删除此任务吗`).then(() => {
            _ipcs.rmItem(id)
        })
        return
    }
    _ipcs.rmItem(id)
}

/*========================================>( 钩子 )<========================================*/
onMounted(() => {
    nowMils.value = new Date().getTime()
    _ipcs.getData()
    setInterval(() => {
        nowMils.value = new Date().getTime()
    }, 1000)
})

</script>
<template>
    <MenuBar title="批量计时器" mid="ModuleCoc" :menus="menuBarMenus" barColor="#222" hideMinimize hideMaximize
        @select="handelBarMenusSelected" />
    <div class="main-content coc">
        <el-collapse v-model="activeIndex" accordion>
            <el-collapse-item v-for="group, index in tasks" :key="index" :name="index">
                <template #title>
                    <div class="collapse-title">
                        <el-icon class="header-icon" :size="20" color="#666">
                            <Folder />
                        </el-icon>
                        <span class="p-r-5-20 text-[#336666]">{{ group.list.length < 10 ? `0${group.list.length}` :
                            group.list.length }}</span>
                                <span class="p-r-5-20">{{ group.labelName }}</span>
                                <div class="p-r-5-30 xw-220 text-center">
                                    <el-progress text-inside :stroke-width="20"
                                        :percentage="taskInfo[group.list.filter((e: any) => (e.createdMils + e.waitMils - new Date().getTime()) > 0)[0]?.id]?.rate"
                                        status="success">
                                        <span class="timenum">
                                            {{taskInfo[group.list.filter((e: any) =>
                                                (e.createdMils + e.waitMils - new Date().getTime()) >
                                                0)[0]?.id]?.remainStr}} </span>
                                    </el-progress>
                                </div>
                                <div v-if="!taskInfo[group.list[0].id]?.status">
                                    <el-tag type="success">有完成项</el-tag>
                                </div>
                    </div>
                </template>
                <div class="item" v-for="item, itemIndex in group.list" :key="itemIndex">
                    <el-icon :size="18" color="#333300">
                        <Clock />
                    </el-icon>
                    <div class="progress p-r-10-10">
                        <el-progress text-inside :stroke-width="30" :percentage="taskInfo[item.id]?.rate"
                            :status="taskInfo[item.id].status ? '' : 'success'">
                            <span class="timenum">{{ taskInfo[item.id]?.remainStr }}</span>
                        </el-progress>
                    </div>
                    <div class="p-r-10-10 text-[#999]">{{ item.note ?? '无备注' }}</div>
                    <el-icon :size="14" color="#666" style="cursor:pointer"
                        @click="handleItemDelete(item.id, taskInfo[item.id].status)">
                        <DeleteFilled />
                    </el-icon>
                </div>
            </el-collapse-item>
        </el-collapse>
        <el-empty v-if="!tasks?.length" description="没有任务，请创建" />
        <add-time v-if="showAddTime" @close="handleAddTimeClose" />
    </div>
</template>
<style lang="scss">
.main-content.coc {
    width: 100%;
    height: calc(100% - 40px);
    overflow: auto;

    .el-progress-bar__outer {
        background-color: rgba(0, 0, 0, 0.2);
    }

    .timenum {
        color: #fff;
        font-weight: bold;
        text-shadow: #000 0 0 3px;
        font-size: 14px;
    }

    .collapse-title {
        font-weight: bold;
        font-size: 15px;
        padding-left: 15px;
        display: flex;
        align-items: center;
    }

    .item {
        width: 49%;
        height: 50px;
        float: left;
        display: flex;
        align-items: center;
        padding-left: 15px;

        .progress {
            width: 130px;
        }

    }

}
</style>
<style lang="scss" scoped>
.main-content {}
</style>
